package bblnamed

import (
	"net"
	"net/http"
	"time"
)

const (
	MAJOR_VERSION       = "0"
	MINOR_VERSION       = "2"
	SERVER_NAME         = "bcs"
	CLUSTER_NAME_PREFIX = "bcs-"
	Author              = "G.Q.F"
	Mail                = "gao.qingfeng@gmail.com"
	License             = "GPL"
)

func version() string {
	return MAJOR_VERSION + "." + MINOR_VERSION
}

func server_name() string {
	return SERVER_NAME + "/" + version()
}

func copyright() string {
	return "Server: " + server_name() + "\nAuthor: " + Author + "\nMail: " + Mail + "\nLicense: " + License
}

type ClusterServer struct {
	Name       string
	Listen     string
	Slaves     []string
	Master     string
	Workdir    string
	Replicas   int
	Passphrase string
	ms         MetadataSystem
	cm         ClusterManager
	listener   net.Listener
}

func (v *ClusterServer) Init() error {
	ll, e := net.Listen("tcp", v.Listen)
	if e != nil {
		log.Error(e)
		return e
	}
	v.listener = ll
	ms, e := NewMetadataSystem(v.Workdir)
	if e != nil {
		log.Error(e)
		return e
	}
	v.ms = ms
	cm, e := NewClusterManager(v.Workdir)
	if e != nil {
		log.Error(e)
		return e
	}
	v.cm = cm

	return nil
}
func (v *ClusterServer) Serve() {
	server := http.Server{
		ReadTimeout:    90 * time.Second,
		WriteTimeout:   90 * time.Second,
		MaxHeaderBytes: 1 << 20,
		Handler:        NewClusterMux(v.cm, v.ms),
	}
	server.SetKeepAlivesEnabled(true)
	log.Info("cluster server " + v.Name + " listen at " + v.Listen)
	server.Serve(v.listener)
}

func (v *ClusterServer) Stop() {
	if v.listener != nil {
		v.listener.Close()
		v.listener = nil
		log.Info("cluster server " + v.Name + " stopped")
	}
	if v.cm != nil {
		v.cm.Close()
		v.cm = nil
	}
	if v.ms != nil {
		v.ms.Close()
		v.ms = nil
	}

}
